<template>
  <div class="main" style="height: 100%">
    <div class="flowform">
      <el-card>
        <el-form ref="form" :model="modelData" label-width="80px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="流程标识" label-width="80px" prop="modelKey">
                <el-input placeholder="请输入流程标识" v-model="modelData.modelKey" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="流程名称" label-width="80px" prop="modelName">
                <el-input placeholder="请输入流程名" v-model="modelData.modelName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="text-align: right">
              <el-form-item>
                <el-button type="primary" @click="queryList">查询</el-button>
                <el-button @click="resetFn">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!--列表-->
      <el-card>
        <div class="formBtn">
          <el-button @click="addForm" icon="el-icon-plus" type="primary">新建流程</el-button>
          <el-button type="info" icon="el-icon-upload2" size="medium" @click="handleImport">导入流程
          </el-button>
        </div>
        <div>
          <el-table :data="tableData" :header-cell-style="{ 'background-color': '#f8f8f9' }" >
            <el-table-column label="流程标识" align="center" prop="key"/>
            <el-table-column label="流程名称" align="center" prop="name"/>
            <el-table-column label="表单信息" align="center" prop="formType">
              <template slot-scope="scope">
                <el-button v-if="scope.row.formId" type="text">
                  <span>{{ scope.row.formName }}</span>
                </el-button>
                <label v-else>暂无表单</label>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180"></el-table-column>
            <el-table-column label="最新部署的流程定义" align="center" prop="processDefinition">
              <el-table-column label="流程版本" align="center" prop="processDefinition.version" width="90">
                <template slot-scope="scope">
                  <el-tag size="medium" v-if="scope.row.processDefinition">v{{
                      scope.row.processDefinition.version
                    }}
                  </el-tag>
                  <el-tag size="medium" type="warning" v-else>未部署</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="激活状态" align="center" prop="state" width="90">
                <template slot-scope="scope">
                  <el-switch v-if="scope.row.processDefinition" v-model="scope.row.processDefinition.suspensionState"
                             :active-value="1" :inactive-value="2" @change="handleChangeState(scope.row)"/>
                </template>
              </el-table-column>
              <el-table-column label="部署时间" align="center" prop="deploymentTime" width="180">
                <template slot-scope="scope">
                  <span v-if="scope.row.processDefinition">{{ scope.row.processDefinition.deploymentTime }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" width="320">
              <template slot-scope="scope">
                <el-dropdown>
                  <span class="el-dropdown-link">
                    表单管理
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="chargeForm(scope.row)">表单绑定</el-dropdown-item>
                    <el-dropdown-item @click.native="formDesign(scope.row)">表单设计</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-dropdown>
                  <span class="el-dropdown-link">
                    流程管理
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="handleDesign(scope.row)">设计流程</el-dropdown-item>
                    <el-dropdown-item @click.native="handleAssignRule(scope.row)">分配规则</el-dropdown-item>
                    <el-dropdown-item @click.native="publishDesign(scope.row)">发布流程</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-dropdown>
                  <span class="el-dropdown-link">
                    更多
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="authorizationManagement(scope.row)">权限管理</el-dropdown-item>
                    <el-dropdown-item @click.native="deleteDesign(scope.row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="pageData.page" :page-sizes="[5, 10, 20, 30]" :page-size="5"
                       layout="total, sizes, prev, pager, next, jumper" :total="pageData.total"></el-pagination>
      </el-card>

      <!--表单弹框-->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="formData" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="流程标识" prop="key">
            <el-input v-model="form.key" placeholder="请输入流标标识" :disabled="formOpen"/>
          </el-form-item>
          <el-form-item label="流程名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入流程名称" :disabled="formOpen" clearable/>
          </el-form-item>
          <el-form-item label="流程描述" prop="description">
            <el-input v-model="form.description" type="textarea" clearable/>
          </el-form-item>
          <el-form-item v-if="formOpen" label="表单选择" prop="formId">
            <el-select v-model="form.formId" clearable placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.formId"
                :label="item.formName"
                :value="item.formId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="save" type="primary">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 分配规则弹窗 -->
      <el-dialog title="任务分配规则" :visible.sync="Assignvisible" width="800px">
        <el-table :data="userRuleData">
          <el-table-column label="任务名称" align="center" prop="taskDefinitionName" width="200"/>
          <el-table-column label="流程标识" align="center" prop="taskDefinitionFlag" width="200"/>
          <el-table-column label="任务标识" align="center" prop="taskDefinitionKey" width="200"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="medium" @click="reviseFn(scope.row)" type="text" icon="el-icon-edit">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <!-- 修改弹窗 -->
      <el-dialog title="修改分配规则" :visible.sync="resizeVisible" width="600px">
        <el-form :model="formResize" ref="formResize">
          <div class="formItemStyle">
            <el-form-item label="任务名称" label-width="80px" prop="taskDefinitionName">
              <el-input v-model="formResize.taskDefinitionName" disabled/>
            </el-form-item>
            <el-form-item label="任务标识" label-width="80px" prop="taskDefinitionKey">
              <el-input v-model="formResize.taskDefinitionKey" disabled/>
            </el-form-item>
          </div>
          <div class="formItemStyle">
            <el-form-item label="流程标识" label-width="80px" prop="taskDefinitionFlag">
              <el-input v-model="formResize.taskDefinitionFlag" disabled style="width: 160px;"/>
            </el-form-item>
          </div>
          <el-form-item label="操作权限" prop="name" label-width="80px">
            <Select multiple v-model="formResize.id">
              <Option v-for="(option, index1) in roleOptions" :value="option.value" :key="'qx' + index1">
                {{ option.label }}
              </Option>
            </Select>
          </el-form-item>
          <el-form-item label="规则类型" prop="type" label-width="80px">
            <Select v-model="personnelResize.type">
              <Option v-for="(option, index2) in personnelOptions" :value="option.value" :key="'ry' + index2">
                {{ option.label }}
              </Option>
            </Select>
          </el-form-item>
          <!--人员-->
          <el-form-item v-show="personnelResize.type === 1" label="指定人员" prop="personneIds" label-width="80px">
            <Select ref="userSelect" v-model="personnelResize.personneIds" multiple filterable>
              <Option v-for="(option, index) in userOptions" :value="option.value" :key="option.value + index">
                {{ option.label }}
              </Option>
            </Select>
          </el-form-item>
          <!--角色-->
          <el-form-item v-show="personnelResize.type === 2" label="指定角色" prop="roleIds" label-width="80px">
            <Select ref="roleSelect" v-model="personnelResize.roleIds" multiple>
              <Option v-for="option in operaterole" :value="option.value" :key="option.value">{{ option.label }}
              </Option>
            </Select>
          </el-form-item>
          <el-form-item label="可编辑字段" label-width="85px">
            <el-checkbox-group v-model="formResize.fieldName">
              <el-checkbox v-for="(option, index3) in fieldOptions" :label="option.value" :key="index3">{{
                  option.label
                }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitResize">确 定</el-button>
            <el-button @click="cancelAssignForm">取 消</el-button>
        </div>
      </el-dialog>
      <!--222权限管理弹框-->
      <el-dialog title="修改权限管理" :visible.sync="authorizationVisible" width="550px" append-to-body>
        <el-form label-width="80px" :model="authpersonnelResize" ref="authpersonnelResize">
          <el-form-item label="流程标识" prop="key">
            <el-input v-model="authpersonnelResize.key" placeholder="请输入流标标识" disabled/>
          </el-form-item>
          <el-form-item label="流程名称" prop="name">
            <el-input v-model="authpersonnelResize.name" placeholder="请输入流程名称" disabled/>
          </el-form-item>
          <el-form-item label="操作权限" prop="type">
            <el-select v-model="authpersonnelResize.type" @change="authpersonnelResizeTypeChange">
              <el-option v-for="option in authpersonnelOptions" :value="option.value" :key="option.value"
                         :label="option.label">
              </el-option>
            </el-select>
          </el-form-item>
          <!--人员-->
          <el-form-item v-show="authpersonnelResize.type === 1" label="指定角色" prop="authroleIds">
            <el-select ref="roleSelect" v-model="authpersonnelResize.authroleIds" multiple>
              <el-option v-for="option in operaterole" :value="option.value" :key="option.value" :label="option.label">
              </el-option>
            </el-select>
          </el-form-item>
          <!--角色-->
          <el-form-item v-show="authpersonnelResize.type === 2" label="指定用户" prop="authpersonneIds">
            <el-select ref="userSelect" v-model="authpersonnelResize.authpersonneIds" multiple filterable>
              <el-option v-for="(option, index) in userOptions" :value="option.value" :key="option.value + index"
                         :label="option.label">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitAuthorization">确 定</el-button>
            <el-button @click="cancelAuthorization">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 用户导入对话框 -->
      <el-dialog title="导入流程" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload ref="upload" :limit="1" accept=".bpmn, .xml, .BPMN, .XML" :headers="upload.headers"
                   :action="upload.url"
                   :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
                   :on-success="handleFileSuccess"
                   :on-error="handleFileError"
                   :auto-upload="false" name="bpmnFile" :data="upload.form" drag
                   style="margin-left:4px">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text" style="margin-left:4px !important">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" style="color:red;text-align: center;margin:0px 0px 15px 0px;" slot="tip">
            提示：仅允许导入“bpmn”或“xml”格式文件！
          </div>
          <div class="el-upload__tip" slot="tip">
            <el-form style="margin-right:5px !important" ref="uploadForm" size="mini" label-width="80px"
                     :model="upload.form"
                     @submit.native.prevent>
<!--              <el-form-item label="流程标识" prop="key">-->
<!--                <el-input v-model="upload.form.key" placeholder="请输入流标标识" style="width: 250px;"/>-->
<!--                <el-tooltip class="item" effect="light" content="新建后，流程标识不可修改！" placement="top">-->
<!--                  <i style="padding-left: 5px;" class="el-icon-question"/>-->
<!--                </el-tooltip>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="流程名称" prop="name">-->
<!--                <el-input v-model="upload.form.name" placeholder="请输入流程名称" clearable/>-->
<!--              </el-form-item>-->
              <el-form-item label="流程描述" prop="description">
                <el-input type="textarea" v-model="upload.form.description" clearable/>
              </el-form-item>
            </el-form>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="uploadClose">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import treeselect from '@riophae/vue-treeselect'

export default {
  components: {
    treeselect
  },
  data () {
    return {
      formResize: {
        taskDefinitionName: '',
        taskDefinitionKey: '',
        taskDefinitionFlag: '',
        id: [],
        formName: '',
        formTable: '',
        fieldName: [],
        idFlag: ''
      },
      personnelResize: {},
      authpersonnelResize: {},
      saveModelId: '',
      ids: '',
      fieldId: [],
      modelData: {
        modelKey: '',
        modelName: ''
      },
      pageData: {
        total: 0,
        pageSize: 5,
        pageNum: 1
      },
      userOptions: [],
      operaterole: [],
      treeArr: [],
      personnelOptions: [
        {
          value: 1,
          label: '人员'
        },
        {
          value: 2,
          label: '角色'
        }
      ],
      authpersonnelOptions: [
        {
          value: 1,
          label: '角色'
        },
        {
          value: 2,
          label: '用户'
        }
      ],
      // 表单校验
      rules: {
        key: [{ required: true, message: '流程标识不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }]
      },
      // 流程导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {
          'Authorization': localStorage.token
        },
        // // 上传的地址
        url: this.$util.baseUrl + '/api/flow/bpmn/import',
        // // 表单
        form: {},
        // // 校验规则
        // rules: {
        //   key: [{ required: true, message: '流程标识不能为空', trigger: 'blur' }],
        //   name: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }]
        // }
      },
      tableData: [],
      userRuleData: [],
      options: [],
      roleOptions: [{
        value: '10',
        label: '传阅'
      },
        {
          value: '11',
          label: '转办'
        }],
      fieldOptions: [],
      modal1: false,
      typeDisabled: false,
      form: {},
      open: false,
      Assignvisible: false,
      authorizationVisible: false,
      resizeVisible: false,
      formOpen: false,
      title: '',
      currentTaskDefinitionKey: ''
    }
  },
  created () {
    this.queryList()
    this.init()
  },
  methods: {
    submitResize () {
      let that = this
      const params1 = {
        taskDefinitionKey: this.formResize.taskDefinitionKey,
        taskDefinitionName: this.formResize.taskDefinitionName,
        taskDefinitionFlag: this.formResize.taskDefinitionFlag,
        perms: !this.formResize.id ? '' : this.formResize.id.join(','),
        id: this.formResize.idFlag || '',
      }
      let promise1 = this.$http.post('/api/flow/rule/taskPerm-update', params1)
      let promise2 = {}
      const params3 = {
        taskDefinitionKey: this.formResize.taskDefinitionKey,
        taskDefinitionName: this.formResize.taskDefinitionName,
        taskDefinitionFlag: this.formResize.taskDefinitionFlag,
        fieldIds: this.formResize.fieldName,
        formId: that.handleAssignRuleRn.formId,
        perm: '0',
      }
      let promise3 = this.$http.post('/api/lowcode/customize/updateTableFieldPerm', params3)
      let personnelResize = {
        ...this.personnelResize
      }
      if (personnelResize.type === 1) {
        personnelResize.options = personnelResize.personneIds
      } else if (personnelResize.type === 2) {
        personnelResize.options = personnelResize.roleIds
      } else if (personnelResize.type === 3) {
        personnelResize.options = personnelResize.treeIds
      }
      personnelResize.personneIds = undefined
      personnelResize.roleIds = undefined
      personnelResize.treeIds = undefined

      if (!personnelResize.id) {
        personnelResize.modelId = that.saveModelId || ''
        promise2 = this.$http.post('/api/flow/rule/assign-create', personnelResize)
      } else {
        promise2 = this.$http.put('/api/flow/rule/update', personnelResize)
      }

      Promise.all([promise1, promise2, promise3]).then(() => {
        this.handleAssignRule(that.handleAssignRuleRn)
        this.resizeVisible = false
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 3000
        })
        this.cancelAssignForm()
      }).catch(() => {
        this.$message({
          message: '修改失败',
          type: 'error',
          duration: 3000
        })
      })
    },
    authpersonnelResizeTypeChange () {
      this.$forceUpdate()
    },

    init () {
      // 人员
      this.$http.get('api/system/cscpUserDetailsOr').then(response => {
        const op = []
        for (let item of response.data.data) {
          op.push({
            value: item.userId,
            label: `${item.username} `
          })
        }
        this.userOptions = op
      }).catch()
      // 角色
      const [url, httpConfig] = [
        '/api/system/cscpRolessByCriteria',
        {
          params: { size: 1000 }
        }
      ]
      this.$http.get(url, httpConfig).then(response => {
        this.operaterole = []
        for (const item of response.data.data) {
          this.operaterole.push({
            value: item.id.toString(),
            label: item.name,
            icon: item.icon
          })
        }
      }).catch()
      // 部门
      this.$http.get('/api/cscpDepts/treeselect').then(res => {
        this.treeArr = res.data
      })
    },

    // 表单设计
    formDesign (row) {
      this.$router.push({
        path: '/lowcode-programming',
        query: {
          key: row.formId
        }
      })
    },

    // 222列表
    queryList () {
      let obj = {}
      obj['key'] = this.modelData['modelKey'] ? this.modelData['modelKey'] : null
      obj['name'] = this.modelData['modelName'] ? this.modelData['modelName'] : null
      let params = Object.assign(obj, {
        page: this.pageData.pageNum,
        size: this.pageData.pageSize
      })
      this.$http
        .get('/api/flow/bpmn/page', {
          params: params
        })
        .then((res) => {
          this.tableData = res.data.result.list
          this.pageData.total = res.data.result.total
        })
        .catch(() => {
          this.$Message.error('列表查询失败')
        })
    },
    addForm () {
      this.title = '新建模型'
      this.open = true
      this.reset()
      this.formOpen = false
    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传失败的处理
    handleFileError (err, file, fileList) {
      const detail = JSON.parse(err.message).detail
      this.$message.error('导入流程失败:' + detail)
      this.uploadClose()
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      if (response.code !== 0) {
        this.$message.error(response.error)
        return
      }
      // 提示，并刷新
      this.$message.success('导入流程成功！请点击【设计流程】按钮，进行编辑保存后，才可以进行【发布流程】')
      // 重置表单

      this.$Message.success('导入成功')
      this.queryList()
      this.uploadClose()
    },
    uploadClose () {
      // 关闭弹窗
      this.upload.open = false
      // 重置上传状态和文件
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      // 重置表单
      this.upload.form = {}
      this.resetForm('uploadForm')
    },
    /** 提交上传文件 */
    submitFileForm () {
      this.$refs['uploadForm'].validate(valid => {
        if (!valid) {
          return
        }
        this.$refs.upload.submit()
      })
    },
    chargeForm (row) {
      this.title = '表单绑定'
      this.open = true
      this.formOpen = true
      this.reset()
      this.form = {
        ...row
      }
      // 查询出设计的流程表列表
      this.getFormAll()
    },
    getFormAll () {
      let obj = {}
      obj['formType'] = '3'
      let params = Object.assign(obj)
      this.$http
        // .get('/api/customizeVforms/', {
        .get('/api/lowcode/customize/cscpCustomizeVforms/listAll', {
          params: params
        })
        .then((res) => {
          this.options = res.data
        })
        .catch(() => {
          this.$Message.error('流程表查询失败')
        })
    },
    // //设计流程
    handleDesign (row) {
      this.$router.push({
        path: '/modelEditor',
        query: {
          modelId: row.id,
          processId: row.key,
          processName: row.name
        }
      })
    },
    // //分配规则
    // initFn () {
    //   this.handleAssignRule()
    // },
    handleAssignRule (row) {
      this.saveModelId = row.id
      this.handleAssignRuleRn = row
      this.formResize.formName = row.formName
      // 调用接口查询
      let obj = {}
      obj['modelId'] = row.id
      obj['processDefinitionId'] = undefined
      let params = Object.assign(obj)
      this.$http.get('/api/flow/rule/list', { params: params })
        .then((res) => {
          res?.data?.result.map(item => item.taskDefinitionFlag = row.key)
          this.userRuleData = res.data.result
        })
        .catch(() => {
          this.$Message.error('任务表查询失败')
        })
      this.Assignvisible = true
    },
    // 点击修改
    reviseFn (row) {
      this.resizeVisible = true
      // 操作配置
      this.formResize.taskDefinitionName = row.taskDefinitionName
      this.formResize.taskDefinitionKey = row.taskDefinitionKey
      this.formResize.taskDefinitionFlag = row.taskDefinitionFlag
      this.ids = row.id
      let param = {
        taskDefinitionKey: row.taskDefinitionKey,
        taskDefinitionFlag: row.taskDefinitionFlag
      }
      // 操作权限数据回显
      this.$http.get('/api/flow/rule/taskPerm-select', { params: param }).then(response => {
        this.formResize.idFlag = ''
        this.formResize.id = ''
        if (response?.data?.result[0]) {
          this.formResize.id = response.data.result[0].perms.split(',')
          this.formResize.idFlag = response.data.result[0].id
        }
      })

      // 人员
      this.personnelResize = {
        ...row,
        personneIds: [],
        roleIds: [],
        treeIds: [],
        options: []
      }
      if (row.type === 1) {
        this.personnelResize.personneIds.push(...row.options)
      } else if (row.type === 2) {
        this.personnelResize.roleIds.push(...row.options)
      } else if (row.type === 3) {
        this.personnelResize.treeIds.push(...row.options)
      }

      // 操作字段权限控制
      let qryTableNameParam = {
        formName: this.formResize.formName
      }
      this.$http.get('/api/lowcode/customize/cscpCustomizeVforms/listOne', { params: qryTableNameParam }).then(response => {
        this.initField(response.data.formTable)
      })
      // 333操作字段权限查询
      this.currentTaskDefinitionKey = row
      this.getKeyName()
    },
    getKeyName () {
      this.$http.get('/api/lowcode/customize/qryTableFieldPerm', {
        params: {
          taskDefinitionKey: this.currentTaskDefinitionKey.taskDefinitionKey,
          taskDefinitionFlag: this.currentTaskDefinitionKey.taskDefinitionFlag
        }
      }).then(response => {
        let temp = response.data.data.map(item => item.fieldId)
        this.formResize.fieldName = temp
      })
    },

    // 字段下拉数据
    initField (tableName) {
      let params = {
        tableName: tableName
      }
      this.$http.get('/api/getTableOperateFields', { params: params }).then(response => {
        this.fieldOptions = []
        for (const item of response.data) {
          this.fieldOptions.push({
            value: item.columnName,
            label: item.columnComment
          })
        }
      }).catch()
    },
    cancelAssignForm () {
      this.personnelResize = {}
      this.resizeVisible = false
      this.$refs.formResize.resetFields()
      this.formResize.id = []
    },
    cancelAssignRuleForm () {
      this.formResize = {}
      this.resizeVisible = false
      this.$refs.formResize.resetFields()
    },
    // 111权限管理

    authorizationManagement (row) {
      this.authpersonnelResize = {
        ...row,
        authpersonneIds: [],
        authroleIds: [],
        relation: [],
        proDefName: '',
        processId: ''
      }
      if (row.type === 2) {
        this.authpersonnelResize.authpersonneIds.push(...row.relation)
      } else if (row.type === 1) {
        this.authpersonnelResize.authroleIds.push(...row.relation)
      }
      if (this.authpersonnelResize.processDefinition) {
        this.getdata()
      } else {
        this.$alert('流程尚未部署，请部署后进行此操作', '提示', {
          confirmButtonText: '确定'
        })
      }
    },

    getdata () {
      this.$http.get(`/api/cscpActs/getAct?id=${this.authpersonnelResize.id}`).then(response => {
        this.authpersonnelResize.type = response.data.type
        this.authorizationVisible = true
        if (response.data.type === 1) {
          this.authpersonnelResize.authroleIds = response.data.relation
        } else {
          this.authpersonnelResize.authpersonneIds = response.data.relation
        }
      }).catch()
    },

    // 权限管理提交

    submitAuthorization () {
      this.$refs.authpersonnelResize.validate(valid => {
        if (valid) {
          // 构建表单
          let authpersonnelResize = {
            ...this.authpersonnelResize,
            // taskDefinitionName: undefined,
            processId: this.authpersonnelResize.processDefinition.id
          }
          if (authpersonnelResize.type === 2) {
            authpersonnelResize.relation = authpersonnelResize.authpersonneIds
          } else if (authpersonnelResize.type === 1) {
            authpersonnelResize.relation = authpersonnelResize.authroleIds
          }
          authpersonnelResize.authpersonneIds = undefined
          authpersonnelResize.authroleIds = undefined
          authpersonnelResize.procDefName = authpersonnelResize.name
          authpersonnelResize.procDefId = authpersonnelResize.id
          this.$http.put('/api/cscpActs/addAct', authpersonnelResize).then(response => {
            this.$Message.success('修改成功')
          }).catch()
          this.authorizationVisible = false
        }
      })
    },
    cancelAuthorization () {
      this.authorizationVisible = false
    },
    // 发布流程
    publishDesign (row) {
      this.$Modal.confirm({
        title: '提示',
        content: '<p>是否发布该流程！</p>',
        onOk: () => {
          this.$http.post('/api/flow/bpmn/deploy?id=' + row.id)
            .then((res) => {
              this.$Message.success('发布成功')
              this.queryList()
            })
            .catch((error) => {
              this.$Message.error('发布失败:' + error.response.data.detail)
            })
        },
        onCancel: () => {
        }
      })
    },
    /** 更新状态操作 */
    handleChangeState (row) {
      const id = row.id
      let state = row.processDefinition.suspensionState
      let statusState = state === 1 ? '激活' : '挂起'
      this.$Modal.confirm({
        title: '提示',
        content: '<p>是否确认' + statusState + '流程:' + row.name + '?</p>',
        onOk: () => {
          const [url, data] = [
            '/api/flow/bpmn/update-state',
            {
              id: id,
              state: state
            }
          ]
          this.$http.put(url, data).then((res) => {
            if (res.data.code === 0) {
              this.$Message.success(statusState + '成功')
              this.queryList()
            }
          }).catch(() => {
            this.$Message.error(statusState + '失败')
          })
          this.reset()
        },
        onCancel: () => {
        }
      })
    },
    // 删除
    deleteDesign (row) {
      this.$Modal.confirm({
        title: '警告',
        content: '<p>确定删除这条数据？</p>',
        onOk: () => {
          let obj = {}
          obj['id'] = row.id
          let params = Object.assign(obj)
          this.$http.delete('/api/flow/bpmn/delete', { params: params })
            .then((res) => {
              this.$Message.success('删除成功')
              this.queryList()
            })
            .catch((error) => {
              this.$Message.error(`${'删除失败！'}<br/>${error.response.data.detail}`)
            })

          this.reset()
        },
        onCancel: () => {
        }
      })
    },

    save () {
      this.$refs.formData.validate(valid => {
        if (!valid) return
        let copyDetail = JSON.parse(JSON.stringify(this.form))
        if (!this.formOpen) {
          this.$http.post('/api/flow/bpmn/create', copyDetail)
            .then((res) => {
              this.$Message.success('新建模型成功')
              this.queryList()
            })
            .catch((error) => {
              this.$Message.error('新建模型失败:' + error.response.data.detail)
            })
        } else {
          this.$http.put('/api/flow/bpmn/update', copyDetail)
            .then((res) => {
              this.$Message.success('更新成功')
              this.queryList()
            })
            .catch((error) => {
              this.$Message.error('更新失败:' + error.response.data.detail)
            })
        }
        this.open = false
        this.formOpen = false
        this.reset()
      })
    },
    resetFn () {
      this.$refs.form.resetFields()
      this.queryList()
    },
    cancel () {
      this.open = false
      this.formOpen = false
      this.form = {}
    },
    reset () {
      this.form = {
        id: undefined,
        key: undefined,
        name: undefined,
        description: undefined
      }

      // this.$nextTick(() => {
      // this.$refs.formData.resetFields()
      if (this.$refs.formData !== undefined) this.$refs.formData.resetFields()
      // })
    },

    submitForm (flag) {
      let obj = {}
      obj['name'] = this.queryForm['name'] ? this.queryForm['name'] : null
      obj['pageNo'] = this.queryForm['pageNo'] ? this.queryForm['pageNo'] : null
      obj['pageSize'] = this.queryForm['pageSize'] ? this.queryForm['pageSize'] : null

      let params = Object.assign(obj)
      this.$http
        // .get('/api/customizeVforms/', {
        .get('/flow/form/page', {
          params: params
        })
        .then((res) => {
          this.data = res.data.data
          this.pageData.total = res.data.recordsTotal
        })
        .catch(() => {
          this.$Message.error('列表查询失败')
        })
    },
    // 分页
    handleSizeChange (val) {
      this.pageData.pageSize = val
      this.queryList()
    },
    handleCurrentChange (val) {
      this.pageData.pageNum = val
      this.queryList()
    }
  }
}
</script>

<style lang="less" scoped>
@import "../admin/styles/formStyle.less";

/deep/ .el-dialog {
  z-index: 1000 !important;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-dropdown {
  margin-right: 14px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}

.el-icon--right {
  margin-left: 0px !important;
}

.el-card {
  margin-bottom: 16px;
}

.el-table__header-wrapper {
  background-color: #f8f8f9;
}

.formBtn {
  float: right;
  margin-bottom: 20px;
}

.el-pagination {
  float: right;
  margin-top: 40px;
}

::v-deep .el-dialog__body {
  overflow: visible;
  overflow: auto;
}

.ivu-tabs {
  overflow: visible;
}

.el-button--primary {
  padding: 8px 15px 8px 15px;
}

.el-button--default {
  padding: 8px 15px 8px 15px;
}

.el-button--info {
  padding: 8px 15px 8px 15px;
}

::v-deep .el-card__body {
  padding: 16px;
}

.formItemStyle {
  display: flex;
}

::v-deep .el-upload-dragger {
  height: 150px;
}

.el-icon-upload {
  margin: 26px 0 16px;
}

</style>
